package com.example.security.util;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.aspectj.lang.ProceedingJoinPoint;

import java.lang.reflect.Field;

public class SqlHelper {
    public static void injectDataPermission(ProceedingJoinPoint point, String permissionSql) {
        try {
            MappedStatement ms = (MappedStatement) point.getArgs()[0];
            BoundSql boundSql = ms.getBoundSql(point.getArgs()[1]);
            String originalSql = boundSql.getSql();
            
            // 在WHERE子句前注入数据权限条件
            String newSql = injectSqlCondition(originalSql, permissionSql);
            
            // 使用反射修改SQL
            Field field = boundSql.getClass().getDeclaredField("sql");
            field.setAccessible(true);
            field.set(boundSql, newSql);
        } catch (Exception e) {
            throw new RuntimeException("注入数据权限SQL失败", e);
        }
    }
    
    private static String injectSqlCondition(String originalSql, String condition) {
        int whereIndex = originalSql.toUpperCase().indexOf(" WHERE ");
        if (whereIndex > 0) {
            return originalSql.substring(0, whereIndex) + 
                   " WHERE " + condition + " AND " + 
                   originalSql.substring(whereIndex + 7);
        } else {
            return originalSql + " WHERE " + condition;
        }
    }
} 